package initializer

import (
	"errors"
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/configure"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"gitee.com/Luna-CY/hui-hui/internal/util/syscall"
	"github.com/spf13/cobra"
	"os"
	"path/filepath"
	"strings"
)

var service = `[Unit]
Description=Hui Hui
Documentation=https://gitee.com/Luna-CY/hui-hui
After=network.target nss-lookup.target

[Service]
Type=simple
Environment=HOME=/root
ExecStart=/opt/huihui/hui-hui run
Restart=on-failure
RestartPreventExitStatus=23

[Install]
WantedBy=multi-user.target`

func run(cmd *cobra.Command, _ []string) error {
	if "" == hostname {
		return errors.New("无效参数，请提供域名选项，可通过--help获取用法")
	}

	if 2 > strings.Count(hostname, ".") {
		return errors.New("Hui-Hui不支持配置为一级域名，请指定二级子域名或三级子域名")
	}

	// 启动前检查
	logger.GetLogger().Sugar().Info("检查系统环境")
	if err := runtime.CheckSystemEnvironment(cmd.Context(), skipCheckHostname, hostname); nil != err {
		return err
	}

	logger.GetLogger().Sugar().Infof("创建路径: %s", runtime.Root)
	if err := os.MkdirAll(runtime.Root, 0755); nil != err {
		return err
	}

	var caddy = GetCaddyApplication()

	// 安装Caddy
	logger.GetLogger().Sugar().Info("安装Caddy服务")
	if err := caddy.Install(cmd.Context(), overwrite); nil != err {
		return err
	}

	// 生成配置
	logger.GetLogger().Sugar().Info("生成HuiHui的默认配置文件")
	if err := configure.GenerateWithInitializer(hostname); nil != err {
		return err
	}

	// 写入系统服务
	logger.GetLogger().Sugar().Info("写入*unix系统服务配置: /etc/systemd/system/hui-hui.service")
	file, err := os.OpenFile(filepath.Join("/etc", "systemd", "system", "hui-hui.service"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if nil != err {
		return err
	}

	defer func() {
		_ = file.Close()
	}()

	if _, err := file.WriteString(service); nil != err {
		return err
	}

	// 配置Caddy
	logger.GetLogger().Sugar().Info("设置Caddy站点配置")
	var tls = &application.CaddyWebsiteTls{Enable: !noTls, Custom: false}
	if "" != tlsCert && "" != tlsKey {
		tls.Custom = true
		tls.CertPath = tlsCert
		tls.KeyPath = tlsKey
	}

	if err := caddy.SetWebsite(cmd.Context(), hostname, []*application.CaddyWebsiteReverse{{Path: "*", Target: fmt.Sprintf("http://127.0.0.1:%d", configure.Configure.Server.Port)}}, tls); nil != err {
		return err
	}

	// 重新加载配置
	logger.GetLogger().Sugar().Info("重载Systemd服务配置`")
	if _, err := syscall.ExecuteCommandGetOutputIgnoreQuitCode(cmd.Context(), "systemctl", "daemon-reload"); nil != err {
		logger.GetLogger().Sugar().Errorf("重载Systemd服务配置失败，原因: %s", err)
	}

	logger.GetLogger().Sugar().Info("初始化完成")

	return nil
}
